package com.gzc.just.play.last.war.robotclient.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.protobuf.gs.gstogc.GSToGC;
import com.gzc.just.play.last.war.robotclient.NettyRobotClient;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@MessageHandler(serverTypes = MessageHandler.ServerType.ROBOT_CLIENT)
public class UserBaseInfoHandler implements SimpleMessageHandler {
    private static final Logger log = LoggerFactory.getLogger(UserBaseInfoHandler.class);

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        GSToGC.UserBaseInfo userInfo = null;
        if (message instanceof byte[]) {
            userInfo = GSToGC.UserBaseInfo.parseFrom((byte[]) message);
        } else if (message instanceof GSToGC.UserBaseInfo) {
            userInfo = (GSToGC.UserBaseInfo) message;
        }

        NettyRobotClient client = ctx.channel().attr(NettyRobotClient.CLIENT_KEY).get();
        if (client == null) {
            log.warn("UserBaseInfoHandler: Robot client not found in channel attributes");
            return;
        }

        if (userInfo != null) {
            log.info("Robot {} Login Gate Success! GUID: {}, Name: {}, Level: {}",
                    client.getRobotId(), userInfo.getGuid(), userInfo.getName(), userInfo.getLevel());

            // Start Heartbeat
            client.startHeartbeat();
        }
    }

    @Override
    public int getMessageId() {
        return 2;
    }

    @Override
    public String getName() {
        return "UserBaseInfoHandler";
    }

    @Override
    public Logger getLogger() {
        return log;
    }
}
